package com.android.love.ui;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.alipay.android.app.sdk.AliPay;
import com.alipay.android.msp.Keys;
import com.alipay.android.msp.Result;
import com.alipay.android.msp.Rsa;
import com.android.love.R;
import com.android.love.net.UriHelper;
import com.android.love.ui.ScreenSlidePageFragment.OnImgClickLister;
import com.android.love.util.ActivityUtil;
import com.android.love.util.LogUtil;
import com.android.love.util.NetworkUtil;
import com.android.love.vo.Meixiu;
import com.android.love.vo.MeixiuOrder;
import com.android.love.vo.MyRequest;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.unionpay.UPPayAssistEx;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class ViewpagerActivity extends BasePageActivity implements
		OnImgClickLister {

	private String[] imgs;

	private long album_id;

	private ViewFinder viewPagerFider;

	private ViewPager viewPager;

	private PagerAdapter mPagerAdapter;

	private FrameLayout fl_back;

	private RelativeLayout rl_title;

	private ImageView iv_back;

	private TextView tv_purchase;

	private TextView tv_title;

	private Meixiu meixiu;
	private AlertDialog singleDialog;
	private String[] pay_type = new String[] { "支付宝（推荐）", "银联支付" };
	private int pay_id;

	private String order_id;

	private String trade_no;

	private static final int RQF_PAY = 1;

	private static final int RQF_LOGIN = 2;

	// private int mGoodsIdx = 0;
	// private Handler mUHandler = null;
	// private ProgressDialog mLoadingDialog = null;

	private static final int PLUGIN_VALID = 0;
	private static final int PLUGIN_NOT_INSTALLED = -1;
	private static final int PLUGIN_NEED_UPGRADE = 2;

	/*****************************************************************
	 * mMode参数解释： "00" - 启动银联正式环境 "01" - 连接银联测试环境
	 *****************************************************************/
	private String mMode = "01";
	// private static final String TN_URL_01 =
	// "http://222.66.233.198:8080/sim/gettn";
	
	private int status=1;

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Result result = new Result((String) msg.obj);

			switch (msg.what) {
			case RQF_PAY:
			case RQF_LOGIN: {
				// Toast.makeText(MyOrderDetail_1.this, result.getResult(),
				// Toast.LENGTH_SHORT).show();
				result.parseResult();
				String statusCode = result.getResultStatus();
				LogUtil.i(TAG, "statusCode--" + statusCode);
				if ("9000".equals(statusCode)) {
					LogUtil.i(TAG, "statusCode--支付成功");
					// 支付成功
					ActivityUtil.show(ViewpagerActivity.this, "支付成功");
					if (NetworkUtil.isAvailable(context)) {
						MyRequest tReq = new MyRequest();
						tReq.authority = UriHelper.REALM_NAME;
						tReq.path = UriHelper.URL_PURCHASE_ALBUM;
						status=2;
						tReq.paramers = generateMyParams();
						MeixiuOrder orderid = null;
						getDataFromTask(context, MEIUXIUTIJIAO, tReq, orderid, true,
								false);
						
					} 

				} else if ("8000".equals(statusCode)) {
					// 支付处理中
					ActivityUtil.show(ViewpagerActivity.this, "支付处理中");
				} else {
					// 支付失败
					Toast.makeText(ViewpagerActivity.this, result.getResult(),
							Toast.LENGTH_SHORT).show();
				}
				// if (statusCode == "4000") {
				// // 支付成功
				// }
				// if (statusCode == "4006") {
				// // 支付成功
				// }
				// if (statusCode == "6001") {
				// // 支付成功
				// }

			}
				break;
			default:
				break;
			}
		};
	};

	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		View viewPagerView = inflater
				.inflate(R.layout.viewpager_activity, null);
		setContentView(viewPagerView);
		viewPagerFider = new ViewFinder(viewPagerView);
		Intent intent = getCurrentIntent();
		if (intent != null) {
			meixiu = (Meixiu) intent.getSerializableExtra("meixiu");
			position = intent.getIntExtra("position", -1);
			album_id = meixiu.getAlbum_id();
		}
		process();
		setListener();
		getData();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.iv_back:
			Intent aintent = new Intent();
			aintent.putExtra("position", position);
			aintent.putExtra("meixiu", meixiu);
			setResult(RESULT_OK, aintent);
			finish(true);
			break;
		case R.id.tv_purchase:
			// finish(true);
			// 购买
			singleDialog = new AlertDialog.Builder(context)
					.setTitle("支付方式")
					.setSingleChoiceItems(pay_type, 0,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									switch (which) {
									case 0:
										pay_id = 2;
										// 提交
										if (NetworkUtil.isAvailable(context)) {
											MyRequest tReq = new MyRequest();
											tReq.authority = UriHelper.REALM_NAME;
											tReq.path = UriHelper.URL_PURCHASE_ALBUM;
											status=1;
											tReq.paramers = generateMyParams();
											MeixiuOrder orderid = null;
											getDataFromTask(context, MEIUXIUTIJIAO,
													tReq, orderid, true, false);
										} else {
											ActivityUtil.show(
													ViewpagerActivity.this,
													"网络错误");
										}
										break;
									case 1:
										// 银联
										pay_id = 3;
										// 提交
										if (NetworkUtil.isAvailable(context)) {
											MyRequest tReq = new MyRequest();
											tReq.authority = UriHelper.REALM_NAME;
											tReq.path = UriHelper.URL_PURCHASE_ALBUM;
											status=1;
											tReq.paramers = generateMyParams();
											MeixiuOrder orderid = null;
											getDataFromTask(context, MEIUXIUTIJIAO,
													tReq, orderid, true, false);
										} else {
											ActivityUtil.show(
													ViewpagerActivity.this,
													"网络错误");
										}
										break;

									default:
										break;
									}
									singleDialog.dismiss();
								}
							}).create();
			singleDialog.show();

			break;

		default:
			break;
		}
	}

	@Override
	protected void process() {
		super.process();
		viewPager = viewPagerFider.find(R.id.pager);
		fl_back = viewPagerFider.find(R.id.fl_back);
		iv_back = viewPagerFider.find(R.id.iv_back);
		rl_title = viewPagerFider.find(R.id.rl_title);
		tv_purchase = viewPagerFider.find(R.id.tv_purchase);
		tv_title = viewPagerFider.find(R.id.tv_title);
		hide(fl_back).hide(rl_title);
	}

	@Override
	protected void setListener() {
		super.setListener();
		iv_back.setOnClickListener(this);
		tv_purchase.setOnClickListener(this);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				LogUtil.i(TAG, "onPageSelected--" + arg0);
				if (arg0 >= 0 && meixiu.getPrice() != 0
						&& meixiu.getPurchased() == 0) {
					show(fl_back).show(rl_title);
					// 收费相册 未付款
					LayoutParams params = new LayoutParams(
							LayoutParams.MATCH_PARENT, ActivityUtil.dip2px(
									context, 120));
					params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
					rl_title.setLayoutParams(params);
					tv_title.setText("此相册为收费相册，如需继续浏览请付款");
					show(tv_purchase);
					tv_purchase.setText("￥" + meixiu.getPrice());
					viewPager.setCurrentItem(0, true);
				} else {
					if (tv_title.getVisibility() == View.VISIBLE
							&& tv_purchase.getVisibility() == View.GONE)
						tv_title.setText(meixiu.getTitle() + "("
								+ (viewPager.getCurrentItem() + 1) + "/"
								+ meixiu.getPhoto_count() + ")");
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				LogUtil.i(TAG, "onPageScrollStateChanged--" + arg0);
			}
		});
	}

	@Override
	protected void getData() {
		super.getData();
		MyRequest req = new MyRequest();
		req.authority = UriHelper.REALM_NAME;
		req.path = UriHelper.URL_PHOTO;
		req.paramers = generateParams(1);
		getDataFromTask(context, PHOTO, req, imgs, true, true);
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateMyParams() {
		JSONObject json = new JSONObject();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		params.put("album_id", album_id + "");
		params.put("cost", meixiu.getPrice() + "");
		params.put("pay_chanel", pay_id + "");
		params.put("status", status+"");
		if (sp.getValue(USER_ID, 0) != 0)
			params.put("user_id", sp.getValue(USER_ID, 0) + "");
		if (!"".equals(sp.getValue(SIG, "")))
			params.put("sig", sp.getValue(SIG, ""));
		return params;
	}

	/**
	 * 得到传递的参数
	 * 
	 * @return
	 * @throws JSONException
	 * @throws IOException
	 */
	public Map<String, String> generateParams(int page) {
		JSONObject json = new JSONObject();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", "android");
		params.put("v", "1.0");
		params.put("page", page + "");
		params.put("count", "10");
		params.put("album_id", album_id + "");
		if (sp.getValue(USER_ID, 0) != 0)
			params.put("user_id", sp.getValue(USER_ID, 0) + "");
		if (!"".equals(sp.getValue(SIG, "")))
			params.put("sig", sp.getValue(SIG, ""));
		return params;
	}

	@Override
	public void handle(int tag, Object object) {
		super.handle(tag, object);
		switch (tag) {
		case PHOTO:
			if (object != null) {
				imgs = (String[]) object;
				mPagerAdapter = new ScreenSlidePagerAdapter(
						getSupportFragmentManager(), imgs);
				viewPager.setSaveEnabled(false);
				viewPager.setAdapter(mPagerAdapter);
				viewPager.setOffscreenPageLimit(1);
			}
			break;

		case MEIUXIUTIJIAO:
			if (object != null) {
				if(status==1){
					if ((MeixiuOrder) object != null) {
						MeixiuOrder meixiuOrder = (MeixiuOrder) object;
						order_id = meixiuOrder.getOrder_no();
						trade_no = meixiuOrder.getTrade_no();
						if (pay_id == 2) {
							// 支付宝
							try {
								Log.i("ExternalPartner", "onItemClick");
								String info = getNewOrderInfo();
								String sign = Rsa.sign(info, Keys.PRIVATE);
								sign = URLEncoder.encode(sign);
								info += "&sign=\"" + sign + "\"&" + getSignType();
								Log.i("ExternalPartner", "start pay");
								// start the pay.
								Log.i(TAG, "info = " + info);

								final String orderInfo = info;
								new Thread() {
									public void run() {
										AliPay alipay = new AliPay(
												ViewpagerActivity.this, mHandler);

										// 设置为沙箱模式，不设置默认为线上环境
										// alipay.setSandBox(true);

										String result = alipay.pay(orderInfo);

										Log.i(TAG, "result = " + result);
										Message msg = new Message();
										msg.what = RQF_PAY;
										msg.obj = result;
										mHandler.sendMessage(msg);
									}
								}.start();

							} catch (Exception ex) {
								ex.printStackTrace();
								Toast.makeText(ViewpagerActivity.this,
										R.string.remote_call_failed,
										Toast.LENGTH_SHORT).show();
							}
						} else if (pay_id == 3) {
							// 银联

							/*************************************************
							 * 
							 * 步骤2：通过银联工具类启动支付插件
							 * 
							 ************************************************/
							// mMode参数解释：
							// 0 - 启动银联正式环境
							// 1 - 连接银联测试环境
							int ret = UPPayAssistEx.startPay(this, null, null,
									trade_no + "", mMode);
							if (ret == PLUGIN_NEED_UPGRADE
									|| ret == PLUGIN_NOT_INSTALLED) {
								// 需要重新安装控件
								Log.e(TAG, " plugin not found or need upgrade!!!");

								AlertDialog.Builder builder = new AlertDialog.Builder(
										this);
								builder.setTitle("提示");
								builder.setMessage("完成购买需要安装银联支付控件，是否安装？");

								builder.setNegativeButton("确定",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
												// 安装Asset中提供的UPPayPlugin.apk
												// 此处可根据实际情况,添加相应的处理逻辑
												UPPayAssistEx
														.installUPPayPlugin(ViewpagerActivity.this);
											}
										});

								builder.setPositiveButton("取消",
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												dialog.dismiss();
											}
										});
								builder.create().show();

							}
							Log.e(TAG, "" + ret);
						}
					}
				}else if(status==2){
					//后台已修改
					meixiu.setPurchased(1);
					LayoutParams params = new LayoutParams(
							LayoutParams.MATCH_PARENT, ActivityUtil.dip2px(context,
									40));
					params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
					rl_title.setLayoutParams(params);
					tv_title.setText(meixiu.getTitle() + "("
							+ (viewPager.getCurrentItem() + 1) + "/"
							+ meixiu.getPhoto_count() + ")");
					hide(tv_purchase);

					mPagerAdapter.notifyDataSetChanged();
					viewPager.setCurrentItem(0);
				}
				
			}

			break;
		default:
			break;
		}
	}

	@Override
	protected Boolean loadBottomTab() {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * A simple pager adapter that represents 5 {@link ScreenSlidePageFragment}
	 * objects, in sequence.
	 */
	private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

		String[] imgs;

		public ScreenSlidePagerAdapter(FragmentManager fragmentManager,
				String[] imgs) {
			super(fragmentManager);
			this.imgs = imgs;
		}

		@Override
		public Fragment getItem(int position) {

			ScreenSlidePageFragment fragment = ScreenSlidePageFragment.create(
					position, imgs);
			fragment.setOnImgClickLister(ViewpagerActivity.this);
			return fragment;
		}

		@Override
		public int getCount() {
			return imgs.length;
		}
	}

	@Override
	public void onImgClick() {
		if (fl_back.getVisibility() == View.GONE) {
			show(fl_back).show(rl_title);
			if (viewPager.getCurrentItem() >= 0 && meixiu.getPrice() != 0
					&& meixiu.getPurchased() == 0) {
				// 收费相册 未付款
				// LayoutParams params=(LayoutParams)
				// rl_title.getLayoutParams();
				LayoutParams params = new LayoutParams(
						LayoutParams.MATCH_PARENT, ActivityUtil.dip2px(context,
								120));
				params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
				rl_title.setLayoutParams(params);
				tv_title.setText("此相册为收费相册，如需继续浏览请付款");
				show(tv_purchase);
				tv_purchase.setText("￥" + meixiu.getPrice());
			} else {
				LayoutParams params = new LayoutParams(
						LayoutParams.MATCH_PARENT, ActivityUtil.dip2px(context,
								40));
				params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
				rl_title.setLayoutParams(params);
				tv_title.setText(meixiu.getTitle() + "("
						+ (viewPager.getCurrentItem() + 1) + "/"
						+ meixiu.getPhoto_count() + ")");
				hide(tv_purchase);
			}
		} else {
			hide(fl_back).hide(rl_title);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_BACK) {
			Intent aintent = new Intent();
			aintent.putExtra("position", position);
			aintent.putExtra("meixiu", meixiu);
			setResult(RESULT_OK, aintent);
			finish(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		/*************************************************
		 * 
		 * 步骤3：处理银联手机支付控件返回的支付结果
		 * 
		 ************************************************/
		if (data == null) {
			return;
		}

		String msg = "";
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		String str = data.getExtras().getString("pay_result");
		if (str.equalsIgnoreCase("success")) {
			msg = "支付成功！";
			ActivityUtil.show(ViewpagerActivity.this, msg);
			if (NetworkUtil.isAvailable(context)) {
				MyRequest tReq = new MyRequest();
				tReq.authority = UriHelper.REALM_NAME;
				tReq.path = UriHelper.URL_PURCHASE_ALBUM;
				status=2;
				tReq.paramers = generateMyParams();
				MeixiuOrder orderid = null;
				getDataFromTask(context, MEIUXIUTIJIAO, tReq, orderid, true,
						false);
			} 
		} else if (str.equalsIgnoreCase("fail")) {
			msg = "支付失败！";
			ActivityUtil.show(ViewpagerActivity.this, msg);
		} else if (str.equalsIgnoreCase("cancel")) {
			msg = "用户取消了支付";
			ActivityUtil.show(ViewpagerActivity.this, msg);
		}

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// builder.setTitle("支付结果通知");
		// builder.setMessage(msg);
		// builder.setInverseBackgroundForced(true);
		// // builder.setCustomTitle();
		// builder.setNegativeButton("确定", new DialogInterface.OnClickListener()
		// {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.dismiss();
		// }
		// });
		// builder.create().show();
	}

	/**
	 * 支付宝订单信息
	 * 
	 * @return
	 */
	private String getNewOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(order_id);
		sb.append("\"&subject=\"");
		// if (order.getGoods().size() == 1)
		// sb.append(order.getGoods().get(0).getGoods_name());
		// else
		sb.append(album_id + "号美秀");
		sb.append("\"&body=\"");
		// if (order.getGoods().size() == 1)
		sb.append(meixiu.getTitle());
		// else
		// sb.append(order.getGoods().size() + "件商品");
		sb.append("\"&total_fee=\"");
		sb.append(meixiu.getPrice());
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder.encode(UriHelper.REALM_NAME+UriHelper.ONLINEPAY));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
